package tools;

import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {

    /*
     * method servlet dibawah ini digunakan untuk filter login dengan memasukkan username, password dan status,
     * lalu mencocokkan dengan data user yang ada pada database.
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        tools.Proses proses = new Proses();
        String req1 = req.getParameter("class");
        String pass = null;
        String userName = null;
        String class2 = null;
        try {
            class2 = proses.isintablestaff(req.getParameter("userName"));
        } catch (SQLException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pass = proses.isintablestaff1(req.getParameter("userName"));
        } catch (SQLException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            userName = proses.isintablestaff2(req.getParameter("userName"));
        } catch (SQLException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (userName == null) {
            RequestDispatcher rd = req.getRequestDispatcher("LOGIN.jsp");
            rd.forward(req, resp);
        } else {
            if (class2.matches("Peminjam")) {
                if (req.getParameter("password").matches(pass) && req.getParameter("class").matches(class2)
                        && req.getParameter("userName").matches(userName) && userName != null) {
                    Peminjam p = new Peminjam();
                    p.setUsername(req.getParameter("userName"));
                    req.getSession().setAttribute("userName", p);
                    resp.sendRedirect("HomePeminjam.jsp");
                } else {
                    RequestDispatcher rd = req.getRequestDispatcher("LOGIN.jsp");
                    rd.forward(req, resp);
                }
            } else if (class2.matches("Staff")) {
                if (req.getParameter("password").matches(pass) && req.getParameter("class").matches(class2)
                        && req.getParameter("userName").matches(userName)) {
                    RequestDispatcher rd = req.getRequestDispatcher("UploadForm.jsp");
                    rd.forward(req, resp);
                } else {
                    RequestDispatcher rd = req.getRequestDispatcher("LOGIN.jsp");
                    rd.forward(req, resp);
                }
            } else {
                RequestDispatcher rd = req.getRequestDispatcher("LOGIN.jsp");
                rd.forward(req, resp);
            }
        }
    }
}
